<!DOCTYPE html>
<html lang="zh">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>计数器示例</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f4f7f6;
            margin: 0;
            padding: 0;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            color: #333;
        }

        .container {
            background-color: #fff;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
            width: 100%;
            max-width: 600px;
            text-align: center;
        }

        h1 {
            font-size: 24px;
            color: #4CAF50;
            margin-bottom: 20px;
        }

        input[type="text"] {
            padding: 8px;
            width: 70%;
            border: 1px solid #ccc;
            border-radius: 4px;
            font-size: 16px;
            margin-bottom: 20px;
            outline: none;
        }

        input[type="text"]:focus {
            border-color: #4CAF50;
        }

        button {
            padding: 10px 20px;
            background-color: #4CAF50;
            border: none;
            color: white;
            font-size: 16px;
            cursor: pointer;
            border-radius: 4px;
            margin-bottom: 20px;
        }

        button:hover {
            background-color: #45a049;
        }

        .output {
            margin-top: 20px;
            padding: 10px;
            background-color: #f1f1f1;
            border-radius: 8px;
            text-align: left;
            word-break: break-word;
            white-space: pre-wrap;
        }

        .output:empty {
            display: none;
        }
    </style>
</head>

<body>
    <div class="container">
        <h1>计数器示例</h1>
        <p>请输入一组数据，使用逗号分隔（例如：1,2,3,1,2,1）:</p>
        <input type="text" id="inputData" placeholder="请输入数据">
        <br>
        <button onclick="calculate()">计算</button>
        <div class="output" id="output"></div>
    </div>

    <script>
        const countBy = (arr, handler) =>
            arr
                .map(typeof handler === 'function' ? handler : val => val[handler])
                .reduce((acc, item) => {
                    acc[item] = (acc[item] || 0) + 1;
                    return acc;
                }, {});

        function calculate() {
            const input = document.getElementById('inputData').value;
            const arr = input.split(',').map(item => item.trim());
            const result = countBy(arr, item => item); // 使用输入的项本身作为分组条件

            let resultText = '各项出现次数:\n';
            for (const key in result) {
                resultText += `${key}: ${result[key]}\n`;
            }

            document.getElementById('output').textContent = resultText;
        }
    </script>
</body>

</html>